package com.fjzn.detect.service.security;

import com.fjzn.detect.repository.enums.UserFlag;
import com.fjzn.detect.repository.enums.UserStatus;
import com.fjzn.detect.repository.user.entity.SysUser;
import com.fjzn.detect.service.exection.BusinessException;
import com.fjzn.detect.service.user.ISysMenuService;
import com.fjzn.detect.service.user.ISysUserService;

import lombok.extern.log4j.Log4j2;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 用户验证处理
 *
 * @author helloworld
 * @since 2021年04月26日10:18:39
 */
@Log4j2
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysMenuService menuService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        SysUser user = userService.selectUserByUserName(username);
        if (Objects.isNull(user)) {
            log.info("登录用户：{} 不存在.", username);
            throw new UsernameNotFoundException("登录用户：" + username + " 不存在");
        } else if (UserFlag.删除.equals(user.getDelFlag())) {
            log.info("登录用户：{} 已被删除.", username);
            throw new BusinessException("对不起，您的账号：" + username + " 已被删除");
        } else if (UserStatus.停用.equals(user.getStatus())) {
            log.info("登录用户：{} 已被停用.", username);
            throw new BusinessException("对不起，您的账号：" + username + " 已停用");
        }

        return createLoginUser(user);
    }

    public UserDetails createLoginUser(SysUser user) {
        return new LoginUser(user, menuService.getMenuPermission(user));
    }
}
